/**
 * Project  : Looker
 * Package  : net.freestu.looker.impl
 * File     : SolaDocMediaListener.java
 * Author   : solosky < solosky772@qq.com >
 * Date     : 2009-9-5
 * Modified : 2009-9-5
 * License  : Apache License 2.0 
 */
package net.freestu.looker.impl;

import java.io.IOException;
import java.net.MalformedURLException;

import net.freestu.looker.common.ListenerException;
import net.freestu.looker.common.Media;
import net.freestu.looker.common.MediaListener;
import net.freestu.looker.util.FileUtils;

import org.apache.commons.configuration.Configuration;
import org.apache.log4j.Logger;
import org.apache.poi.POITextExtractor;
import org.apache.poi.extractor.ExtractorFactory;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.solr.client.solrj.SolrResponse;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.apache.xmlbeans.XmlException;

/**
 *  
 */
public class SolaDocMediaListener implements MediaListener
{
	/**
	 * solr服务器对象
	 */
	 private CommonsHttpSolrServer solrServer;
	 
	 /**
	  * solr服务器回复
	  */
	 private SolrResponse response;
	 
	 /**
	  * logger
	  */
	 private static Logger logger = Logger.getLogger(SolaDocMediaListener.class);

	/* (non-Javadoc)
	 * @see net.freestu.looker.common.MediaListener#add(net.freestu.looker.common.Media)
	 */
	@Override
	public void add(Media media) throws ListenerException
	{
		//只添加文档类型的
		if(media.getType().equals(FileUtils.FileType.DOC)) {
			
			//用PIO提取正文
			String text = null;
            try {
            	POITextExtractor ext = ExtractorFactory.createExtractor(media.getTmpFile());
	        	text = ext.getText();
            } catch (InvalidFormatException e) {
	         throw new ListenerException("文档格式错误:"+e+" - "+media);
            } catch (IOException e) {
            	 throw new ListenerException("文档读取错误:"+e+" - "+media);
            } catch (OpenXML4JException e) {
            	 throw new ListenerException("OpenXML4J解析错误:"+e+" - "+media);
            } catch (XmlException e) {
            	 throw new ListenerException("XML解析错误:"+e+" - "+media);
            }
			SolrInputDocument doc = new SolrInputDocument();
			doc.addField("hash", media.getHash());
			doc.addField("title",parseTitle(text));//提取正文前第一个回车符为标题
			doc.addField("text",text);
			doc.addField("url", media.getUrl());
			doc.addField("date",media.getDate().getTime()/1000);
			doc.addField("from", media.getNewsEntity().getUrl());
			doc.addField("ext",FileUtils.extension(media.getTmpFile().getName()));
			doc.addField("size", media.getSize());
			
			try {
	            response = solrServer.add(doc);
	            logger.info("SolrNewsAdd:"+response);
            } catch (SolrServerException e) {
	           throw new ListenerException("solr服务器内部错误"+e);
            } catch (IOException e) {
            	 throw new ListenerException("solr服务器读取错误"+e);
            }
			
			
		}

	}

	/* (non-Javadoc)
	 * @see net.freestu.looker.common.MediaListener#close()
	 */
	@Override
	public void close() throws ListenerException
	{
		// TODO Auto-generated method stub

	}

	/* (non-Javadoc)
	 * @see net.freestu.looker.common.MediaListener#commit()
	 */
	@Override
	public void commit() throws ListenerException
	{
		 try {
		        response = solrServer.commit();
		        logger.info("commit:"+response.getResponse());
			    response = solrServer.optimize();
			    logger.info("optimze:"+response.getResponse());
	        } catch (SolrServerException e) {
		        throw new ListenerException("提交更改时solr服务器内部出错:"+e.getMessage());
	        } catch (IOException e) {
	        	throw new ListenerException("提交更改时IO出错:"+e.getMessage());
	        }

	}

	/* (non-Javadoc)
	 * @see net.freestu.looker.common.MediaListener#delete(net.freestu.looker.common.Media)
	 */
	@Override
	public void delete(Media media) throws ListenerException
	{
		// TODO Auto-generated method stub

	}

	/* (non-Javadoc)
	 * @see net.freestu.looker.common.MediaListener#init(org.apache.commons.configuration.Configuration)
	 */
	@Override
	public void init(Configuration conf) throws ListenerException
	{
		String solrUrl = conf.getString("solrDocUrl");
		try {
			logger.info(solrUrl);
	        solrServer = new CommonsHttpSolrServer(solrUrl);
        } catch (MalformedURLException e) {
	        throw new ListenerException("初始化错误:"+e);
        }
        logger.info("初始化完成");
	}

	/* (non-Javadoc)
	 * @see net.freestu.looker.common.MediaListener#update(net.freestu.looker.common.Media)
	 */
	@Override
	public void update(Media media) throws ListenerException
	{
		// TODO Auto-generated method stub

	}
	
	
	private String parseTitle(String text)
	{
		int p = text.indexOf('\n');
		String ret = null;
		if(p>30) {
			
			ret = text.substring(0,p);
		}else {
			ret =  text.substring(0,30);
		}
		return ret;
	}

}
